from odoo import http, fields
from odoo.http import request
import json


class HostelStudentController(http.Controller):

    @http.route('/my_hostel/students', type='http', auth='public')
    def hostel_students_html(self, **kwargs):
        """HTML格式展示hostel_student数据"""
        try:
            # 获取所有学生数据 - 直接传递Odoo记录对象
            students = request.env['hostel.student'].sudo().search([])
            
            # 渲染HTML模板
            return request.render('my_hostel.hostel_students_template', {
                'students': students,
                'total_count': len(students),
                'current_time': fields.Datetime.now().strftime('%Y-%m-%d %H:%M:%S')
            })
            
        except Exception as e:
            return request.render('my_hostel.hostel_students_error_template', {
                'error_message': str(e)
            })

    @http.route('/my_hostel/students/json', type='http', auth='public', methods=['GET'])
    def hostel_students_json(self, **kwargs):
        """JSON格式展示hostel_student数据"""
        try:
            # 获取查询参数
            limit = int(kwargs.get('limit', 100))
            offset = int(kwargs.get('offset', 0))
            status = kwargs.get('status', '')
            hostel_id = kwargs.get('hostel_id', '')
            
            # 构建搜索域
            domain = []
            if status:
                domain.append(('status', '=', status))
            if hostel_id:
                domain.append(('hostel_id', '=', int(hostel_id)))
            
            # 获取学生数据
            students = request.env['hostel.student'].sudo().search(domain, limit=limit, offset=offset)
            total_count = request.env['hostel.student'].sudo().search_count(domain)
            
            # 准备JSON数据
            student_data = []
            for student in students:
                # 安全获取关联字段数据
                room_data = {}
                if student.room_id:
                    room_data = {
                        'id': student.room_id.id,
                        'room_no': student.room_id.room_no,
                        'name': student.room_id.name or student.room_id.room_no
                    }
                else:
                    room_data = {'id': None, 'room_no': None, 'name': None}
                
                student_data.append({
                    'id': student.id,
                    'name': student.name,
                    'gender': student.gender,
                    'class_id': student.class_id or None,  # class_id is Char field, not Many2one
                    'hostel_id': {
                        'id': student.hostel_id.id if student.hostel_id else None,
                        'name': student.hostel_id.name if student.hostel_id else None
                    },
                    'room_id': room_data,
                    'check_in_date': student.check_in_date.isoformat() if student.check_in_date else None,
                    'check_out_date': student.check_out_date.isoformat() if student.check_out_date else None,
                    'stay_duration': student.stay_duration or 0,
                    'status': student.status,
                    'active': student.active,
                    'create_date': student.create_date.isoformat() if student.create_date else None,
                    'write_date': student.write_date.isoformat() if student.write_date else None,
                })
            
            # 返回JSON响应
            response_data = {
                'success': True,
                'data': student_data,
                'meta': {
                    'total_count': total_count,
                    'returned_count': len(student_data),
                    'limit': limit,
                    'offset': offset,
                    'timestamp': fields.Datetime.now().isoformat()
                }
            }
            
            return request.make_json_response(response_data)
            
        except Exception as e:
            import traceback
            error_response = {
                'success': False,
                'error': {
                    'message': str(e),
                    'type': type(e).__name__,
                    'traceback': traceback.format_exc()
                },
                'timestamp': fields.Datetime.now().isoformat()
            }
            return request.make_json_response(error_response, status=500)

    @http.route('/my_hostel/student/<int:student_id>', type='http', auth='public')
    def hostel_student_detail(self, student_id, **kwargs):
        """获取单个学生的详细信息"""
        try:
            student = request.env['hostel.student'].sudo().browse(student_id)
            if not student.exists():
                return request.render('my_hostel.hostel_student_not_found_template', {
                    'student_id': student_id
                })
            
            # 直接传递Odoo记录对象
            return request.render('my_hostel.hostel_student_detail_template', {
                'student': student
            })
            
        except Exception as e:
            return request.render('my_hostel.hostel_students_error_template', {
                'error_message': str(e)
            })
